﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using IGolovkine.Core.Diagnostics;
using IGolovkine.Core;

namespace IGolovkine.ShoutCastRipper
{
    public class ContentTitleProbingPolicy : IContentTitleProbingPolicy
    {
        private readonly ILogWriter _logWriter;
        private readonly TimeSpan _probingFrequency;
        private readonly Timer _timer;
        
        public event EventHandler<EventArgs> ContentTitleProbingDue;

        private DateTime _nextReconnectAttempt;
        private readonly ObjectDisposedCheck _disposedCheck;

        public ContentTitleProbingPolicy(TimeSpan probingFrequency, ILogWriter logWriter)
        {
            Debug.NotDefault(() => probingFrequency);
            Debug.NotDefault(() => logWriter);
            _probingFrequency = probingFrequency;
            
            _timer = new Timer(new TimerCallback(this.OnTimerCallBack));
            _nextReconnectAttempt = DateTime.MaxValue;
            _logWriter = logWriter;
            _disposedCheck = new ObjectDisposedCheck(this);
        }

        private void OnTimerCallBack(object state)
        {
            this.OnContentTitleProbingDue(EventArgs.Empty);
        }

        protected virtual void OnContentTitleProbingDue(EventArgs args)
        {
            if (this.ContentTitleProbingDue != null)
            {
                this.ContentTitleProbingDue(this, args);
            }
        }

        public void ScheduleToReconnect(Exception reason)
        {
            _disposedCheck.EnsureNotDisposed();
            _nextReconnectAttempt = DateTime.Now + _probingFrequency;
            _timer.Change(_probingFrequency, TimeSpan.FromMilliseconds(-1));
        }
        
        public void Dispose()
        {
            _disposedCheck.Dispose();
            _timer.Dispose();
        }
    }
}
